package com.lmx.repoDomain.repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.unpersis.ExportThreadParam;

import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiResourceRepository;

@JsonApiResourceRepository(ExportThreadParam.class)
@Component
public class ExportThreadParamRepository
		extends BaseRepository<ExportThreadParam> {
	@Override
	public Iterable<ExportThreadParam> findAll(
			final QueryParams requestParams) {
		List<ExportThreadParam> list = Lists.newArrayList();
		Map<String, String> filter = CommonUtil
				.getKeyMapByFilter(requestParams);
		if (!filter.containsKey("url")) {
			throw new BusinessException(null,
					ICommonConstants.EXPORT_ERROR.URL_NULL.lable(), "url不能为空");
		}
		Map<String, ExportThreadParam> map = Maps
				.newHashMap(ActionContextHolder.getExportThreadMap());
		Pattern pattern = Pattern.compile("\\d{14}");
		Matcher matcher = pattern.matcher(filter.get("url"));
		if (matcher.find()) {
			String idStr = matcher.group();
			ExportThreadParam rtn = map.get(idStr);
			if (rtn != null) {
				rtn.setId(Long.valueOf(idStr));
				rtn.setStatusValue(rtn.getStatus().getValue());
				list.add(rtn);
			} else {
				throw new BusinessException("",
						ICommonConstants.EXPORT_ERROR.DATA_MISS.lable(),
						"导出数据丢失,重新尝试导出");
			}
		}
		return list;
	}
}
